﻿using AutoMapper;
using Modules;
using Modules.Corp;
using Modules.Project;
using PmSoft;
using Modules.System.User;
using Modules.Common;
using PmSoft.ApplicationContext;
using PmSoft.Entity;

namespace ManagementApi.Models.Device
{
    public class AppCheckinAuthDto : OperateDto
    {
        /// <summary>
        /// 主键
        ///</summary>
        public int Id { get; set; }

        /// <summary>
        /// 项目id
        ///</summary>
        public int ProjectId { get; set; }

        /// <summary>
        /// 参建单位id
        ///</summary>
        public int CorpId { get; set; }

        /// <summary>
        /// 开始日期
        ///</summary>
        public DateTime StartDate { get; set; }

        /// <summary>
        /// 结束日期
        ///</summary>
        public DateTime EndDate { get; set; }

        /// <summary>
        /// 是否禁用
        ///</summary>
        public bool IsDisable { get; set; }

        /// <summary>
        /// 创建时间
        ///</summary>
        public DateTime CreateTime { get; set; }

        /// <summary>
        /// 最后一次修改时间
        ///</summary>
        public DateTime LastUpdateTime { get; set; }

        #region 扩展字段

        public string ProjectName { get; set; }

        public string CorpName { get; set; }

        #endregion 扩展字段
    }

    public static partial class PAppCheckinAuthExceptions
    {
        public static AppCheckinAuthDto AsDto(this AppCheckinAuth entity, IApplicationContext applicationContext)
        {
            AppCheckinAuthDto dto = new();
            var mapper = applicationContext.GetService<IMapper>();
            mapper.Map(entity, dto);
            var corpService = applicationContext.GetService<CorpService>();
            dto.CorpName = corpService.GetCorpInfo(entity.CorpId??0)?.Name ?? string.Empty;
            var projectService = applicationContext.GetService<ProjectService>();

            var projectInfo = projectService.GetProjectInfo(entity.ProjectId);
            if (projectInfo != null)
            {
                dto.ProjectName = projectInfo.Name;

                #region 主管单位数据权限

                if (applicationContext.CurrentUser is IDeptUser deptUser)
                {
                    if (deptUser.IsSuperAdministrator() || projectInfo.DeptId == deptUser.DeptId)
                        dto.HasEdit = true;
                    else dto.HasEdit = false;
                }

                #endregion 主管单位数据权限
            }
            return dto;
        }
    }
}